package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Course;
import cn.kgc.vue.exceptions.StudentNoException;
import cn.kgc.vue.mapper.CourseMapper;
import cn.kgc.vue.mapper.ScheduleMapper;
import cn.kgc.vue.service.ScheduleService;
import cn.kgc.vue.vo.StudentVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Student;
import cn.kgc.vue.service.StudentService;
import cn.kgc.vue.mapper.StudentMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 11839
* @description 针对表【sys_student】的数据库操作Service实现
* @createDate 2024-06-28 15:23:44
*/
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService{


    @Resource
    private CourseMapper courseMapper;

    @Resource
    private ScheduleMapper scheduleMapper;

    @Override
    public ResponseResult studentPage(QueryCondition<Student> student) {
        Integer page = student.getPage();
        Integer limit = student.getLimit();
        Student searchParams = student.getSearchParams();
        //创建分页条件
        Page<Student> studentPage = new Page<>(page, limit);
        //获取搜索条件
        String studentNo = searchParams.getStudentNo();
        String clazz = searchParams.getClazz();

        //根据搜索条件 构造动态sql
        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(StringUtils.isNotBlank(studentNo),Student::getStudentNo, studentNo)
                .eq(StringUtils.isNotBlank(clazz),Student::getClazz, clazz)
                .orderByDesc(Student::getSchoolYear);
         baseMapper.selectPage(studentPage,lambda);

        List<Student> records = studentPage.getRecords();
        long total = studentPage.getTotal();


        //由于课程名称在数据库中不是直接写的 需要通过课程来查该课程名称
        List<StudentVo> collect = records.stream().map(student1 -> {
            StudentVo studentVo = new StudentVo();
            BeanUtils.copyProperties(student1, studentVo);
            Integer courseId = student1.getCourseId();
            String clazz1 = student1.getClazz();
            String courseName = courseMapper.selectAllIncludingDeletedById(courseId).getCourseName();
            String classNo = scheduleMapper.selectAllIncludingDeletedById(clazz1).getClassNo();
            studentVo.setCourseName(courseName);
            studentVo.setClassName(classNo);

            return studentVo;
        }).collect(Collectors.toList());







        return ResponseResult.success().data("total", total).data("tableData", collect);
    }

    @Transactional
    @Override
    public ResponseResult importStudent(MultipartFile file) throws Exception {
        if (file.isEmpty()){
            return ResponseResult.fail().message("文件为空,请传入文件");
        }

        //创建一个导入参数
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);

        InputStream inputStream = file.getInputStream();

        List<Student> students = ExcelImportUtil.importExcel(inputStream, Student.class, importParams);

        students.forEach(student -> {
            try{
                baseMapper.insert(student);
            }catch (DuplicateKeyException e){
                 throw  new StudentNoException(student.getStudentNo());
            }

        });


        return ResponseResult.success().message("导入成功");
    }

    @Override
    public ResponseResult exportStudent(HttpServletResponse response, Map<String, Object> exportParam) throws IOException {

        Object studentNo = exportParam.get("studentNo");
        Object clazz = exportParam.get("clazz");

        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(ObjectUtils.isNotNull(studentNo),Student::getStudentNo,studentNo)
                .eq(ObjectUtils.isNotNull(clazz),Student::getClazz,clazz);

        List<Student> students = baseMapper.selectList(lambda);

        //创建导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("学生信息表");
        exportParams.setSheetName("学生信息");

        // 工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, students);
        ServletOutputStream outputStream = response.getOutputStream();

        // 写出工作簿
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();

        return ResponseResult.success().message("导出成功");
    }













}




